cc.Class({
    extends: cc.Component,

    properties: {
        item: cc.Node,
        layout: cc.Node,
    },

    onEnable() {
        this.lobbyMain = cc.find("Canvas").getComponent("lobbyMain");
        this.lobbyNet = this.lobbyMain.lobbyNet;
        this.playerInfo = this.lobbyMain.playerInfo;
        this.emailInfo = this.playerInfo.emailInfo;
        this.emptyLabel = this.node.getChildByName("ScrollView").getChildByName("view").getChildByName("emtpy");
        this.sortEmail();  //邮件排序
        this.emailContent = this.node.getChildByName("emailContent");
        this.setEmail();  //放置邮件
        this.emailId = 0;
    },

    start() {

    },

    onClick(event, target) {
        this.lobbyMain.playClickSound();
        if (target == "close") {
            this.lobbyMain.hidePanel(this.node);
        } else if (target == "item") {
            this.emailId = event.target.emailId;
            this.showEmail(this.emailId);  //显示邮件
        } else if (target == "delete") {  //删除邮件
            let id = event.target.parent.emailId;
            this.deleteEmail(id);
        } else if (target == "closeEmail") {  //关闭邮件
            this.closeEmail();
        } else if (target == "ok") {
            this.readEmail(); // 已读
        } else if (target == "receive") {
            this.receiveEmail();  //接收邮件
        }
    },

    //放置邮件
    setEmail() {
        this.layout.removeAllChildren();
        // if (this.emailInfo.length > 0) {
        //     this.emptyLabel.active = false;
        // }
        for (let i = 0; i < this.emailInfo.length; i++) {
            const element = this.emailInfo[i];

            if (element.delete) {
                continue;
            }
            this.emptyLabel.active = false;
            let item = cc.instantiate(this.item);
            if (element.read == 0) {  //未读
                item.getChildByName("weidu").active = true;
            } else {
                item.getChildByName("yidu").active = true;
            }
            item.getChildByName("title").getComponent(cc.Label).string = element.title;
            let contentNode = item.getChildByName("content");
            let label = contentNode.getComponent(cc.Label);

            let maxLength = 20;
            if (element.content.length > maxLength) {
                label.string = element.content.substring(0, maxLength) + "...";
            } else {
                label.string = element.content;
            }

            if (!element.read) {
                item.getChildByName("Delete").getComponent(cc.Button).interactable = false;
            } else {
                item.getChildByName("Delete").getComponent(cc.Button).interactable = true;
            }

            item.emailId = element.id;
            this.layout.addChild(item);
        }
    },


    sortEmail() {
        this.emailInfo.sort(function (a, b) {
            // 先按 read 排序（未读优先）
            if (a.read !== b.read) {
                return a.read - b.read;  // 0在前，1在后
            }
            // 再按 time 排序（时间从大到小）
            return b.time - a.time;
        });
    },

    //展示邮件
    showEmail(id) {
        let info = this.emailInfo.find(element => element.id == id);
        this.emailContent.active = true;
        this.lobbyMain.showPanel(this.emailContent);
        let tankuangNode = null
        if (info.mailType == "1") {  //文本邮件
            tankuangNode = this.emailContent.getChildByName("tankuang1")
        } else if (info.mailType == "2") {  //金币邮件
            tankuangNode = this.emailContent.getChildByName("tankuang2")
        }
        if (info.read) {
            tankuangNode.getChildByName("receive").getComponent(cc.Button).interactable = false;
        } else {
            tankuangNode.getChildByName("receive").getComponent(cc.Button).interactable = true;
        }
        tankuangNode.active = true;
        tankuangNode.getChildByName("title").getComponent(cc.Label).string = info.title;
        tankuangNode.getChildByName("content").getComponent(cc.Label).string = info.content;
        if (info.mailType == "2") {
            tankuangNode.getChildByName("kuang2").getChildByName("label").getComponent(cc.Label).string = (info.coin / this.playerInfo.ratio).toFixed(2);
        }
    },

    //已读邮件 
    readEmail() {
        this.lobbyMain.openLoading();
        this.closeEmail();
        let info = this.emailInfo.find(element => element.id == this.emailId);
        if (info.read) {
            return
        }
        let data = {
            action: "readEmail",
            playerId: this.playerInfo.playerId,
            emailId: this.emailId
        }
        this.lobbyNet.sendMessage(data);
    },


    // 关闭邮件
    closeEmail() {

        let callback = () => {
            this.emailContent.getChildByName("tankuang1").active = false;
            this.emailContent.getChildByName("tankuang2").active = false;
        }

        this.lobbyMain.hidePanel(this.emailContent, callback);
    },


    // 接受邮件
    receiveEmail() {
        this.lobbyMain.openLoading();
        this.closeEmail();
        let info = this.emailInfo.find(element => element.id == this.emailId);
        if (info.read) {
            return
        }
        let data = {
            action: "receiveEmail",
            playerId: this.playerInfo.playerId,
            emailId: this.emailId,
            coin: info.coin
        }
        this.lobbyNet.sendMessage(data);
    },

    //删除邮件
    deleteEmail(id) {
        this.lobbyMain.openLoading();
        let data = {
            action: "deleteEmail",
            playerId: this.playerInfo.playerId,
            emailId: id
        }
        this.lobbyNet.sendMessage(data);
    },

    //已读邮件的返回
    onReadEmailResponse(data) {
        this.lobbyMain.loading.active = false;
        for (let i = 0; i < this.playerInfo.emailInfo.length; i++) {
            const element = this.playerInfo.emailInfo[i];
            if (element.id == data.data.id) {
                this.playerInfo.emailInfo[i] = data.data;
            }
        }
        this.sortEmail();
        this.setEmail();
    },


    //领取邮件的返回
    onReceiveEmailResponse(data) {
        this.lobbyMain.loading.active = false;
        for (let i = 0; i < this.playerInfo.emailInfo.length; i++) {
            const element = this.playerInfo.emailInfo[i];
            if (element.id == data.email.id) {
                this.playerInfo.emailInfo[i] = data.email;
            }
        }
        let coin = data.coin / this.playerInfo.ratio.toFixed(2);
        this.playerInfo.playerCoin = parseFloat(coin)
        this.lobbyMain.updateUserCoin();
        this.sortEmail();
        this.setEmail();
        this.lobbyMain.showTips("Coins claimed successfully");
    },

    //删除邮件的返回
    onDeleteEmailResponse(data) {
        this.lobbyMain.loading.active = false;
        if (data.respCode != "FAIL") {
            for (let i = 0; i < this.playerInfo.emailInfo.length; i++) {
                const element = this.playerInfo.emailInfo[i];
                if (element.id == data.data.id) {
                    this.playerInfo.emailInfo[i] = data.data;
                }
            }
            this.sortEmail();
            this.setEmail();
        } else {
            this.lobbyMain.showTips(data.message);
        }

    },


    // update (dt) {},
});
